package aspect;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

/**
 * 切面类
 */
@Component
@Aspect//声明该类为切面类
public class SpringAspect {
    private static SqlSessionFactory factory;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint point) throws IllegalAccessException {
        SqlSession session = factory.openSession();
        Object targetObj = point.getTarget();
        Field[] fieldArray = targetObj.getClass().getDeclaredFields();
        for (Field f : fieldArray) {
            if (f.getType().isInterface()) {
                Object obj = session.getMapper(f.getType());
                f.setAccessible(true);
                f.set(targetObj, obj);
            }
        }
        Object returnObj = null;
        try {
            try {
                returnObj = point.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        } finally {
            session.close();
        }
        return returnObj;
    }
}
